package ls.jpa.chapterD.model;


import ls.jpa.chapterD.value.BookValue;

import javax.persistence.*;
import java.io.Serializable;

@Entity

// ========================== 整合POJO查询
@SqlResultSetMappings(@SqlResultSetMapping(name = "bookValue", classes = {@ConstructorResult(targetClass = BookValue
        .class, columns = {@ColumnResult(name = "id", type = Long.class), @ColumnResult(name = "title", type = String
        .class), @ColumnResult(name = "version", type = Long.class), @ColumnResult(name = "authorName", type = String
        .class)})}))
@NamedNativeQueries(@NamedNativeQuery(name = "Author.findBookValueWithoutImpl", query = "SELECT b.id, b.title, b.version, CONCAT(a.firstName, ' ', a.lastName) as authorName FROM Book b JOIN Author a ON b.author_id = a.id",resultSetMapping = "bookValue"))
// ==========================整合JPA查询
@NamedQueries(@NamedQuery(name = "Author.findByFirstName", query = "select o from Author o where o.firstName = ?1"))

public class Author implements Serializable {

    private static final long serialVersionUID = 8259964999956117105L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", updatable = false, nullable = false)
    private Long id;
    @Version
    @Column(name = "version")
    private int version;

    @Column
    private String firstName;

    @Column
    private String lastName;

    public Long getId() {
        return this.id;
    }

    public void setId(final Long id) {
        this.id = id;
    }

    public int getVersion() {
        return this.version;
    }

    public void setVersion(final int version) {
        this.version = version;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof Author)) {
            return false;
        }
        Author other = (Author) obj;
        if (id != null) {
            if (!id.equals(other.id)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        return result;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        String result = getClass().getSimpleName() + " ";
        if (firstName != null && !firstName.trim().isEmpty()) {
            result += "firstName: " + firstName;
        }
        if (lastName != null && !lastName.trim().isEmpty()) {
            result += ", lastName: " + lastName;
        }
        return result;
    }
}